package ca.michaelmaguire.server.mobiledownload.server;

import ca.michaelmaguire.server.mobiledownload.server.entity.AppContents;
import ca.michaelmaguire.server.mobiledownload.server.entity.AppEvent;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import javax.jdo.Query;

import com.google.appengine.api.datastore.KeyFactory;

public class FileListServlet extends BaseRecordingServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -808894634175346118L;
	private static final Logger log = Logger.getLogger(FileListServlet.class
			.getName());

	public void doGet(HttpServletRequest aHttpServletRequest,
			HttpServletResponse aHttpServletResponse) throws ServletException,
			IOException {
		try {

			recordEvent(aHttpServletRequest, (String) null, AppEvent.VISIT);

			String responseString = null;

			responseString = "Files:";

			PersistenceManager pm = PMF.get().getPersistenceManager();

			// List all 'primary' app contents (i.e. all one which don't have a
			// parent file so we only show jad, not jar).
			Query query = pm
					.newQuery("select from ca.michaelmaguire.server.mobiledownload.server.entity.AppContents"
							+ " where parentappcontents == null"
							+ " order by filename asc");

			List<AppContents> results = (List<AppContents>) query.execute();

			if (results.iterator().hasNext()) {
				for (AppContents appContents : results) {

					String fileKey = KeyFactory.keyToString(appContents
							.getKey());

					responseString += "\n</p> <a href=\"/download?"
							+ HeaderConstants.NAME_APP + "=" + fileKey + "\"> "
							+ appContents.getFileName() + " "
							+ appContents.getUser() + " " + fileKey + "</a>";

				}
			} else {

				responseString += "\n No items.";

			}

			// Ensure that we mark our response so that browsers and mobile
			// transcoders don't attempt to cache or transform the returned
			// files.
			aHttpServletResponse.addHeader("Pragma", "no-cache");
			aHttpServletResponse
					.addHeader("Cache-Control",
							"private, no-cache, no-store, proxy-revalidate, no-transform");

			aHttpServletResponse.setContentType("text/html");
			ServletOutputStream sos = aHttpServletResponse.getOutputStream();
			sos.write(responseString.getBytes());

		} catch (Exception aException) {
			throw new ServletException(aException);
		}
	}
}